package com.lblin.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.Timer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class ServerSocket {

	public static void main(String[] args) throws IOException {

		new Timer().schedule(new TimerTaskDemo(), 5000, 60000);

		// 创建通道组 （线程池）
		AsynchronousChannelGroup group = AsynchronousChannelGroup.withFixedThreadPool(6, new ThreadFactory() {

			private byte index = 0;

			public Thread newThread(Runnable r) {
				// TODO Auto-generated method stub
				return new Thread(r, "lblin-aio-serverThread-" + (++index));
			}
		});

		// 创建服务端，绑定端口，使用上面创建的线程池处理端口监听的工作
		final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group)
				.bind(new InetSocketAddress(8080), 2000);

		System.out.println("服务端启动");

		server.accept(null, new CompletionHandler<AsynchronousSocketChannel, String>() {

			public void completed(AsynchronousSocketChannel result, String attachment) {

				server.accept(attachment, this);

				while (result.isOpen()) {

					// System.out.println("服务端连接成功！当前处理线程为："+Thread.currentThread().getName());

					ByteBuffer buffer = ByteBuffer.allocate(1024);

					Future<Integer> future = result.read(buffer);
					try {
						TimerTaskDemo.sendPacket.addAndGet(future.get());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ExecutionException e) {
						// TODO Auto-generated catch block
						System.out.println(e.getMessage());
						try {
							result.close();
							continue;
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					// buffer.flip();
					// System.out.println("服务端接收到的数据为"+new
					// String(buffer.array()));
					// //连接成功
					// System.out.println("响应客户端的内容为：我收到了！");

					try {
						result.write(ByteBuffer.wrap("我收到了！".getBytes(Charset.forName("UTF-8")))).get();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ExecutionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}

			public void failed(Throwable exc, String attachment) {
				// TODO Auto-generated method stub
				exc.printStackTrace();
			}

		});

		new ClientSocket().init();
	}

}
